﻿using AvaVSExt.Attributes;
using AvaVSExt.Helpers;
using System.IO;

namespace AvaVSExt
{
    public partial class Program
    {
        [VSCommand("newview")]
        public static void CreateNewView()
        {
            var info = VSHelper.GetSelectedItemInfoInSolutionExplorer();
            if (info is null) return;
            if (info.ItemType != ItemType.Folder) return;
            var rootNamespace = CsprojHelper.GetRootNamespace(info.ProjectFullPath);
            var namespaceName = info.GetNamespaceName(rootNamespace);

            if (InputBoxHelper.Show("请输入文件名", "请输入文件名", "NewView", out var viewName))
            {
                var dir = info.ItemFullPath;
                NewView.CreateNewViewCode(dir, viewName, namespaceName);
            }
        }
    }

    public static class NewView
    {
        public static void CreateNewViewCode(string dir, string viewName, string namespaceName)
        {
            CreateNewViewAxaml(dir, viewName, namespaceName);
            CreateNewViewCs(dir, viewName, namespaceName);
        }

        private static void CreateNewViewAxaml(string dir, string viewName, string namespaceName)
        {
            var localShortName = Xmlns.GetNamespaceShortName(namespaceName);
            var file = Path.Combine(dir, viewName + ".axaml");
            var code = $@"<UserControl xmlns=""https://github.com/avaloniaui""
             xmlns:x=""http://schemas.microsoft.com/winfx/2006/xaml""
             xmlns:d=""http://schemas.microsoft.com/expression/blend/2008""
             xmlns:mc=""http://schemas.openxmlformats.org/markup-compatibility/2006""
             xmlns:{localShortName}=""using:{namespaceName}""
             mc:Ignorable=""d"" d:DesignWidth=""800"" d:DesignHeight=""450""
             x:Class=""{namespaceName}.{viewName}"">
  Welcome to Avalonia!
</UserControl>
";


            File.WriteAllText(file, code);
        }

        private static void CreateNewViewCs(string dir, string viewName, string namespaceName)
        {
            var file = Path.Combine(dir, viewName + ".axaml.cs");

            var code = $@"using Avalonia;
using Avalonia.Controls;
using Avalonia.Markup.Xaml;

namespace {namespaceName};

public partial class {viewName} : UserControl
{{
    public {viewName}()
    {{
        InitializeComponent();
    }}
}}";

            File.WriteAllText(file, code);
        }

    }
}
